﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System.Text;
using System.Data;
using System.IO;
using System.Collections;
using Newtonsoft.Json;
using System.Xml;
using System.Xml.Serialization;

namespace LeSoft.Application.Web.Areas.QualificationManage.Controllers
{
    public class FirstTrialController : MvcControllerBase
    {
        //
        // GET: /QualificationManage/FirstTrial/Index
        //初审
        private QualificationBillBLL QFBbll = new QualificationBillBLL();
        private MaterialSeedBLL MSbll = new MaterialSeedBLL();
        private MaterialRuleBLL MRbll = new MaterialRuleBLL();
        private QalificationMaterialRuleBLL QMRbll = new QalificationMaterialRuleBLL();

        #region 视图
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "初审首页", "Index")]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "初审详情", "Form")]
        public ActionResult Form()
        { 
             return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "材料", "MSettingForm")]
        public ActionResult MSettingForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "材料详情", "AddForm")]
        public ActionResult AddForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "材料规则", "MSettingRuleForm")]
        public ActionResult MSettingRuleForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "规则详情", "RSettingForm")]
        public ActionResult RSettingForm()
        {
            return View();
        }


        #endregion

        #region 获取数据

        /// <summary>
        /// 获取初审状态树
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "初审状态树", "GetTreeListTojson")]
        public ActionResult GetTreeListTojson()
        {
            string str = EnumAttribute.GetDescription(QStateEnum.Checked).Substring(0, 5);
            List<TreeStatusEntity> lst = new List<TreeStatusEntity>();
            lst.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(QStateEnum.All), QStateEnum.All.ToString(), 0));
            lst.Add(new TreeStatusEntity(QStateEnum.All.ToString(), EnumAttribute.GetDescription(QStateEnum.FirstCheck), QStateEnum.FirstCheck.ToString(), 0));
            lst.Add(new TreeStatusEntity(QStateEnum.All.ToString(), EnumAttribute.GetDescription(QStateEnum.AgainCheck), QStateEnum.AgainCheck.ToString(), 0));
            lst.Add(new TreeStatusEntity(QStateEnum.All.ToString(), EnumAttribute.GetDescription(QStateEnum.AllCheck), QStateEnum.AllCheck.ToString(), 0));
            lst.Add(new TreeStatusEntity(QStateEnum.AllCheck.ToString(), EnumAttribute.GetDescription(QStateEnum.UnChecked), QStateEnum.UnChecked.ToString(), 0));
            lst.Add(new TreeStatusEntity(QStateEnum.AllCheck.ToString(), str, QStateEnum.Checked.ToString(), 0));
            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (TreeStatusEntity item in lst)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = lst.Count(t => t.PValue == item.Value) == 0 ? false : true;
                tree.id = item.Value;
                tree.text = item.Text;
                tree.value = item.Value;
                if (item.PValue == "0") tree.isexpand = true;
                else tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.PValue;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        /// <summary>
        /// 分页获取获取单据列表
        /// </summary>
        /// <param name="type"> 1-初审 2-复审</param>
        /// <param name="pagination">分页参数</param>
        /// <param name="queryJson">  查询参数json:State StartTime EndTime Name IDCard Phone</param>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "单据列表", "GetPageList")]
        public ActionResult GetPageList(Pagination pagination, string queryJson)
        {
            var data = QFBbll.GetPageList(3, pagination, queryJson);
            var watch = CommonHelper.TimerStart();
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        /// <summary>
        /// 获取申请单实体
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetForm, "获取申请单实体", "GetEntity")]
        public ActionResult GetEntity(string keyValue)
        {
            var data = QFBbll.GetEntity(keyValue);

            //单据信息
            //申请人信息
            var MemberInfo = new
            {
                //通讯地址
                //邮编
                //民族
                Name = "",
                IDCard = "",
                Sex = "",
                Cultural = "",
                Phone = "",
                PhoneNum = "",
                MarryInfo = "",
                HouseholdAddress = "",
                HasLiveCard = "",
                LiveCard = "",
                LiveCardFull2Year = "",
                HasSocialSecurityFund = "",
                SocialSecurityFullYear = "",
                HasProvidentFund = "",
                ProvidentFundCard = "",
                CompanyName = "",
                CompanyPhone = "",
                CompanyType = "",
                CompanyAddress = "",
                CompanyPostalCode = ""
            };

            //共同申请人信息
            List<ResidentInfoEntity> list1 = new List<ResidentInfoEntity>();
            //申请人本市户籍地住房情况
            List<MemberRoomInfoEntity> list2 = new List<MemberRoomInfoEntity>();
            //申请人拥有本市产权住房情况
            List<MemberRoomInfoEntity> list3 = new List<MemberRoomInfoEntity>();
            //申请人承租本市共有住房情况
            List<MemberRoomInfoEntity> list4 = new List<MemberRoomInfoEntity>();
            //附件


            var datalist = new
            {
                QualificationBill = data,
                MemberInfo = MemberInfo,
                ResidentInfo = list1,
                MemberRoomInfo1 = list2,
                MemberRoomInfo2 = list3,
                MemberRoomInfo3 = list4
            };
            return Content(datalist.ToJson());
        }

        /// <summary>
        /// 获取单据信息
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>  
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetForm, "获取单据信息", "GetBillInfo")]
        public ActionResult GetBillInfo(string keyValue)
        { 
            var data = QFBbll.GetBillInfo(keyValue);
            return Content(data);
        }

        /// <summary>
        /// 获取资料上传规则集合
        /// </summary>
        /// <returns></returns> 
        ///  
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "获取资料上传规则集合", "GetMaterialRuleList")]
        public ActionResult GetMaterialRuleList()
        {
            var data = MRbll.GetList().OrderBy(e => e.Sort).ToList();
            data = data.Where(e => e.Type == "2").ToList();
            return Content(data.ToJson());

        }
        /// <summary>
        /// 获取资料上传规则
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns> 
        /// 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetForm, "获取资料上传规则实体", "GetMaterialRuleEntity")]
        public ActionResult GetMaterialRuleEntity(string keyValue)
        {
            var data = MRbll.GetEntity(keyValue);
            return Content(data.ToJson());
        }


        /// <summary>
        /// 获取材料规则
        /// </summary>
        /// <param name="keyValue">材料ID</param>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取材料规则", "GetRuleList")]
        public ActionResult GetRuleList()
        {
            var data = QMRbll.GetList();
            List<Object> lst = new List<object>();
            var json1 = new
            {
                Id = "",
                MarryInfo = "未婚无子女",
                IsPermant = GetNumber(1, 1),
                YDLiveCard = GetNumber(1, 0)
            };
            lst.Add(json1);
            var json8 = new
            {
                Id = "",
                MarryInfo = "未婚有子女",
                IsPermant = GetNumber(8, 1),
                YDLiveCard = GetNumber(8, 0)
            };
            lst.Add(json8);
            var json2 = new
            {
                Id = "",
                MarryInfo = "已婚无子女",
                IsPermant = GetNumber(2, 1),
                YDLiveCard = GetNumber(2, 0)
            };
            lst.Add(json2);
            var json3 = new
            {
                Id = "",
                MarryInfo = "已婚有子女",
                IsPermant = GetNumber(3, 1),
                YDLiveCard = GetNumber(3, 0)
            };
            lst.Add(json3);
            var json4 = new
            {
                Id = "",
                MarryInfo = "离婚、离异无子女",
                IsPermant = GetNumber(4, 1),
                YDLiveCard = GetNumber(4, 0)
            };
            lst.Add(json4);
            var json5 = new
            {
                Id = "",
                MarryInfo = "离婚、离异有子女",
                IsPermant = GetNumber(5, 1),
                YDLiveCard = GetNumber(5, 0)
            };
            lst.Add(json5);
            var json6 = new
            {
                Id = "",
                MarryInfo = "丧偶无子女",
                IsPermant = GetNumber(6, 1),
                YDLiveCard = GetNumber(6, 0)
            };
            lst.Add(json6);
            var json7 = new
            {
                Id = "",
                MarryInfo = "丧偶有子女",
                IsPermant = GetNumber(7, 1),
                YDLiveCard = GetNumber(7, 0)
            };
            lst.Add(json7);

            
           
            return Content(lst.ToJson());
        }
        /// <summary>
        /// 材料树
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "材料树", "GetMaterialTree")]
        public ActionResult GetMaterialTree()
        {
            var data = MRbll.GetList().OrderBy(t => t.Sort).ToList();
            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (MaterialRuleEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = false;
                tree.id = item.Code;
                tree.text = item.Sort + "." + item.Name;
                tree.isexpand = true;
                tree.value = item.Code;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.img = "fa";
                tree.parentId = "0";
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        //
        private string GetNumber(int a, int b)
        {
            string str = "";
            var data = QMRbll.GetList();
            data = data.Where(e => e.MarrayInfo == a && e.IsPermant == b).ToList();
            int i = 0;
            foreach (var item in data)
            {
                if (i == 0)
                {
                    str += MRbll.GetEntity(item.Materialld) == null ? "" : MRbll.GetEntity(item.Materialld).Sort.ToString();
                }
                else
                {
                    str += MRbll.GetEntity(item.Materialld) == null ? "" : " 、" + MRbll.GetEntity(item.Materialld).Sort.ToString();
                }
                i++;
            }
            return str;
        }
        #endregion

        #region 保存数据
        /// <summary>
        /// 初审（审核申请人信息）
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="Memo"></param>
        /// <param name="State"></param>
        /// <returns></returns>
        ///   
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "初审审核", "SubmitForm")]
        public ActionResult SubmitForm(string keyValue, string Memo, string State)
        {
            QualificationBillCheckRecordEntity entity = new QualificationBillCheckRecordEntity();
            entity.BillId = keyValue;
            entity.Category = 1;
            entity.CheckFlag = Convert.ToInt32(State);
            entity.CheckDate = DateTime.Now;
            entity.CheckMan = OperatorProvider.Provider.Current().UserName;
            entity.CheckManId = OperatorProvider.Provider.Current().UserId;
            if (State == "0")
            {
                entity.CheckMemo = Memo;
            }
            entity.Date = DateTime.Now;
            entity.Type = 1;
            try
            {
                QFBbll.CheckBillInfo(1, entity);
                return Success("提交成功");
            }
            catch (Exception e)
            {
                //  return Success("提交成功");
                return Error("提交失败：" + e.Message);
            }
        }

        /// <summary>
        /// 保存资料上传规则
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="entity">资料实体</param>
        /// <returns></returns>

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存材料上传规则", "SaveMaterialRuleEntity")]
        public ActionResult SaveMaterialRuleEntity(string keyValue, MaterialRuleEntity entity)
        {
            entity.Type = "2";
            entity.IsSubmit = entity.IsUpload == 1 ? 1 : entity.IsSubmit;
            try
            {
                MRbll.SaveForm(keyValue, entity);
                return Success("保存成功");
            }
            catch (Exception e)
            {
                return Error("保存失败:" + e.Message);
            }

        }
        /// <summary>
        /// 删除上传规则实体
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Delete, "删除上传规则实体", "RemoveMaterialRuleEntity")]
        public ActionResult RemoveMaterialRuleEntity(string keyValue)
        {
            try
            {
                MRbll.RemoveForm(keyValue);
                return Success("删除成功");
            }
            catch (Exception e)
            {
                return Error("删除失败：" + e.Message);
            }
        }
        /// <summary>
        /// 保存材料配置
        /// </summary>
        /// <param name="MarryInfo">婚姻状况</param>
        /// <param name="MarryInfoText">婚姻状况描述</param>
        /// <param name="IsPermant">是否本地户籍</param>
        /// <param name="Data">草料集合</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存材料配置", "SaveQRMForm")]
        public ActionResult SaveQRMForm(string MarryInfo, string MarryInfoText, string IsPermant, string Data)
        {
            List<QalificationMaterialRuleEntity> list = new List<QalificationMaterialRuleEntity>();
            string ss = Data.Substring(1);
            ss = ss.Substring(0, ss.Length - 1);
            string[] Lst = ss.Split(',');
            for (int i = 0; i < Lst.Length; i++)
            {
                QalificationMaterialRuleEntity entity = new QalificationMaterialRuleEntity();
                entity.Materialld = Lst[i].ToString();
                entity.IsPermant = Convert.ToInt32(IsPermant);
                entity.MarrayInfo = Convert.ToInt32(MarryInfo);
                entity.MarrayInfoText = MarryInfoText;
                list.Add(entity);
            }
            try
            {

                QMRbll.SaveForm(list);
                SaveXML();
                return Success("保存成功！");
            }
            catch (Exception e)
            {

                return Error("保存失败：" + e.Message);
            }
        }
        #endregion

        #region 保存材料配置文本
        public void SaveXML()
        {
            List<QalificationMaterialRuleEntity> List = new List<QalificationMaterialRuleEntity>();
            List<QalificationMaterialRuleEntity> list = QMRbll.GetList();
            foreach (var item in list)
            {
                MaterialRuleEntity enty = MRbll.GetEntity(item.Materialld);
                if (!enty.IsEmpty())
                {
                    item.MarrayInfoText = enty.Description;
                    item.Id = enty.Name;
                    List.Add(item);
                }
            }
            try
            {
                string Url = HttpRuntime.AppDomainAppPath.ToString();
                string xml = List.ToJson().ToString();
                Url += "Resource/MaterialInfoXML.txt";
                FileStream fsWriter = new FileStream(Url, FileMode.Create, FileAccess.Write);
                byte[] bf = Encoding.UTF8.GetBytes(xml);
                fsWriter.Position = 0;
                fsWriter.Write(bf, 0, bf.Length);
                fsWriter.Close();
                fsWriter.Dispose();
            }
            catch (Exception)
            {
                throw;
            }

        }
        #endregion



        #region 数据导出
        /// <summary>
        /// 资料导出
        /// </summary>
        public ActionResult GetExportList(string queryJson)
        {
             new ExportBLL().GetExportList((int)ExportType.FirstQB, queryJson);
            return Success("导出成功。");
        }
        #endregion
    }

}